package com.spring.mvc.dao.impl;

import static com.spring.mvc.util.ErrCode.ERROR;
import static com.spring.mvc.util.ErrCode.SUCCESS;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.googlecode.ehcache.annotations.Cacheable;
import com.googlecode.ehcache.annotations.TriggersRemove;
import com.spring.mvc.dao.UserDAO;
import com.spring.mvc.mapper.UserMapper;
import com.spring.mvc.pojo.CallResult;
import com.spring.mvc.pojo.User;
import com.spring.mvc.util.Prompt;

@Component
public class UserDAOImpl implements UserDAO {
	
	protected static Logger logger=LoggerFactory.getLogger(UserDAOImpl.class);

	@Autowired
	private UserMapper userMapper;

	/**
	 * process user login
	 */
	public CallResult login(User user) {
		logger.debug("method:login");
		CallResult cr=new CallResult();
		List<User> users=userMapper.login(user.getUserName(), user.getUserPwd());
		if(null != users && users.size() > 0){
			cr.setErrInfo(SUCCESS, Prompt.get("success"));
			user=users.get(0);
			user.setUserPwd("");
			user.setUserPwd2("");
			cr.setObject(users.get(0));
		}else{
			logger.debug("user login failed! "+user.toString());
			cr.setErrInfo(ERROR, Prompt.get("error"));
		}
		return cr;
	}

	/**
	 * check username is exists
	 */
	public CallResult check(String userName) {
		logger.debug("method:check");
		CallResult result=new CallResult();
		User user=userMapper.checkUserName(userName);
		if(null != user){
			result.setErrInfo(ERROR, Prompt.get("user.exists"));
		}else{
			result.setErrInfo(SUCCESS, Prompt.get("user.notexists"));
		}
		return result;
	}

	@TriggersRemove(cacheName="userCache")
	public CallResult addUser(User user) {
		logger.info("method: addUser");
		CallResult result=new CallResult();
		int i=userMapper.insert(user);
		if(i >= 0){
			result.setErrInfo(SUCCESS, Prompt.get("success"));
			result.setObject(user);
		}else{
			logger.debug("user register failed:"+user.toString());
			result.setErrInfo(ERROR, Prompt.get("error"));
		}
		return result;
	}

	@Cacheable(cacheName="userCache")
	public CallResult list() {
		CallResult result=new CallResult();
		List<User> list=userMapper.list();
		result.setObject(list);
		return result;
	}
}
